{% extends "base.html" %}

{% block head %}
<script src="{{ settings.MEDIA_URL }}js/anytime.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="{{ settings.MEDIA_URL }}css/anytime.css"/>
<script>
$(document).ready(function () {
    var plottedData = [];

    getTsStats = function (ts_pk) {
        $.ajax({
          url: '/timeseries/',
          data: {'timeseries': ts_pk, 'action':'stats'},
          success: function (data){
                        $('#id_start_time').attr('value',data['start_time']);
                        $('#id_end_time').attr('value',data['end_time']);

                        $('#id_start_time').AnyTime_noPicker();
                        $('#id_end_time').AnyTime_noPicker();

                        $('#id_start_time').AnyTime_picker({earliest:data['start_time']});
                        $('#id_end_time').AnyTime_picker({latest:data['end_time']});

                        $('#id_number_of_samples').attr('value',data['number_of_samples']);
                   },
          dataType:'json',
          beforeSend: function () { $('#loading').fadeIn() },
          complete: function() { $('#loading').fadeOut() },
          })
    };
   
    plotNewData = function(series) {
        plottedData.push(series);
        $.plot($('#graph'), plottedData, options);
        refreshRemoverButtons(plottedData);
    };

    ajaxError = function() {
        alert('There was a problem with your request. Make sure you are not requesting a higher sample rate than the original sample rate.');
    };

    //Due to my supreme laziness, this options object is for both the ajax form and the Flot graph! Maybe fix that...
    var options = {
        dataType: 'json',
        success: plotNewData,
        beforeSend: function () { $('#loading').fadeIn() },
        error: ajaxError,
        complete: function() { $('#loading').fadeOut() },
        xaxis: {mode:'time'},
        selection: { mode: "xy" }
        }

{% if auto_click_submit %}
    $("option[value='JSON']").attr('selected','selected');
    $('#ts_form').ajaxSubmit(options);
{% endif %}

    refreshRemoverButtons = function(plottedData){
        // show the header for the remover buttons
        $('#removerLabel').attr('visibility','show')

        // blank the list of remover buttons
        $('#alreadyFetched').replaceWith("<div class='center alreadyFetched' id='alreadyFetched'></div>");
        // for each shown plot
        $.each(plottedData,
            // create a remove button
            function(index, value){

                $('#alreadyFetched').append("<p><input type='submit' class='alreadyFetched' value='Remove "+ value['label'] +"' id='remove"+ value['label'] +"'></p>");
                $('input:last').click(function() {
                    plottedData.splice(index,1)
                    $.plot($('#graph'), plottedData, options);
                    $(this).remove();
                    refreshRemoverButtons(plottedData);
                });

             });        
    };

    $('#ts_form').submit(
        function() {
            if ($("option[value='matlab']").attr('selected') || $("option[value='csv']").attr('selected')){
                return true; 
                }
            else {
                $(this).ajaxSubmit(options);
                alert('submitting ajax');
                return false;
                }
        }
    );

    $('#id_start_time').AnyTime_picker();
    $('#id_end_time').AnyTime_picker();

    $('#id_timeseries').change(
        function(){
            getTsStats(this.value)
        })

    var plot = $.plot($('#graph'),
    plottedData,
     {xaxis: {mode:"time"}, selection: { mode: "xy" }, points: { show: true}, lines: {show: true}, color: "Black", clickable: true, hoverable: true}
     );

    // setup overview
    var overview = $.plot($("#{{timeseries.id}}_overview_graph_id"), [plottedData], {
        selection: { mode: "xy" },  xaxis: { mode:'time'}
    });

    $("#graph").bind("plotselected", function (event, ranges) {
        // clamp the zooming to prevent eternal zoom
        if (ranges.xaxis.to - ranges.xaxis.from < 0.00001)
            ranges.xaxis.to = ranges.xaxis.from + 0.00001;
        if (ranges.yaxis.to - ranges.yaxis.from < 0.00001)
            ranges.yaxis.to = ranges.yaxis.from + 0.00001;
        
        // do the zooming
        alert('zooming');
        plot = $.plot($("#graph"), [plottedData],
                      $.extend(true, {}, { title:'{{timeseries}}',  xaxis: { mode:'time'}, selection: { mode: "xy" }, points: { show: true}, lines: {show: true}, color: "Black", clickable: true, hoverable: true}, {
                          xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
                          yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
                      }));
        
        // don't fire event on the overview to prevent eternal loop
        overview.setSelection(ranges, true);
    });

    $("#{{timeseries.id}}_overview_graph_id").bind("plotselected", function (event, ranges) {
        plot.setSelection(ranges);
    });

});

</script>

{% endblock head %}

{% block content%}
<h3>Timeseries browser</h3>

<div id="graph" class="big center">
</div>

<h2>Get data</h2>
<form action="/timeseries/" method="GET" id="ts_form">
<table class="center">
{{ts_form.as_table}}
<tr><td colspan=2><input type="submit" value="Do it!" /></td></tr>
</table>
</form>

<h2 id="removerLabel" style="display:hidden;">Remove data from the plot</h2>
<div class="center" id="alreadyFetched">
</div>
</form>

{% endblock content%}
